package com.richard.base.view

import android.content.Context
import android.graphics.Color
import android.text.SpannableString
import android.text.SpannableStringBuilder
import android.text.Spanned
import android.text.TextPaint
import android.text.style.ClickableSpan
import android.util.AttributeSet
import android.view.View
import androidx.appcompat.widget.AppCompatTextView


/**
 ***************************************
 * 项目名称:kaishustory
 * @Author wuzhiguo
 * 邮箱：wuzhiguo@ksjgs.com
 * 创建时间: 2020/8/26     9:46 AM
 * 用途:
 ***************************************
 */
class ReplyTextView @JvmOverloads constructor(
        context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : AppCompatTextView(context, attrs, defStyleAttr) {

    private lateinit var mReplyInfo: ReplyInfo

    /**
     * 谁回复谁中回复字符串，可以变成别的
     */
    private var mTalkStr = ":"
    /**
     * 文字大小，单位sp
     */
    //    private int mTextSize = 10;
    /**
     * 人名称颜色
     */
    private var mNameColor: Int = Color.parseColor("#9B9B9B")
    private var mCommentColor: Int = Color.parseColor("#4A4A4A")

    public fun setReplyInfo(replyInfo: ReplyInfo) {
        this.mReplyInfo = replyInfo
        text = getCommentString()
    }

    private fun getCommentString(): SpannableStringBuilder {
        val mStringBuilder = SpannableStringBuilder()
        var mS: String? = mReplyInfo.nickname + mTalkStr + mReplyInfo.comment
        val mString = SpannableString(mS)


        var start = 0
        var end = 0
        end = mReplyInfo.nickname.length + mTalkStr.length

        /**
         * 处理第一个人名
         * 设置文本从第0个开始到end位置具有点击事件，点击后回调，updateDrawState中设置文本从第0个到第end位置的文本前景色就是文字颜色为橘红色
         */
        mString.setSpan(object : ClickableSpan() {
            override fun onClick(widget: View) {

            }

            override fun updateDrawState(ds: TextPaint) {
                /**
                 * 是否有下划线
                 */
                ds.isUnderlineText = false
                ds.color = mNameColor
            }


        }, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)


        start = mReplyInfo.nickname.length + mTalkStr.length
        end = mReplyInfo.nickname.length + mTalkStr.length + mReplyInfo.comment.length
        mString.setSpan(object : ClickableSpan() {
            override fun updateDrawState(ds: TextPaint) {
                /**
                 * 是否有下划线
                 */
                ds.isUnderlineText = false
                ds.color = mCommentColor
            }

            override fun onClick(widget: View) {

            }
        }, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)

        return mStringBuilder.append(mString)
    }


    class ReplyInfo(
            /**
             * 评论人名称
             */
            val nickname: String,
            /**
             * 评论内容
             */
            val comment: String
    )
}